package com.ximu.test.base.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static Socket socket;
	public static void main(String[] args){
		
		try{
			System.out.println("开始监听:");
			//1.创建服务端
			ServerSocket server = new ServerSocket(2012);
			//2.监听客户端请求
			socket = server.accept();
			//3.得到socket输入
			BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//4.得到socket输出
			PrintWriter socketWriter = new PrintWriter(socket.getOutputStream());
			BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
			
			String clientString = null;
			System.out.println("有客户端:");
			class ListenerSocket extends Thread{
				@Override
				public void run() {
					System.out.println("开始监听数据:");
					try{
						BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						String str = socketReader.readLine();
						while(!str.equals("quit")){
							System.out.println("Client:"+str);
							str = socketReader.readLine();
						}
						System.out.println("quit");
					}catch(IOException e){
						System.out.println("错误");
					}
					super.run();
				}

			}
			Thread listenerThread = new Thread(new ListenerSocket());
			listenerThread.start();
			System.out.println("等待输入:");
			String inputString = input.readLine();
			while(!inputString.equals("quit")){
//				System.out.println("Server:"+inputString);
				socketWriter.println(inputString);
				socketWriter.flush();
				inputString = input.readLine();
			}
			input.close();
			socketWriter.close();
			socketReader.close();
			socket.close();
			server.close();
		}catch(IOException e){
			System.out.println("错误");
		}
	}
}
